//
//  WeiboAtController.m
//  yuikemall
//
//  Created by yuike5 yuike5 on 12-3-16.
//  Copyright (c) 2012年 yuike. All rights reserved.
//
#import "WeiboAtController.h"
#import "UIViewAdditions.h"
#import "UIColorAdditions.h"
#import "NSStringAdditions.h"
#import "NSString+Extension.h"
#import "header.h"
#import "QQShare.h"

#define TEXT_FIELD_ID 234
#define TABLE_VIEW_ID 457
#define FILTER_BTN_ID 345

@implementation WeiboAtRootView
-(void) setFrame:(CGRect)frame {
    [super setFrame:frame];
    
    UITextField* textField = (UITextField*)[self viewWithTag:TEXT_FIELD_ID];
    UITableView* tableView = (UITableView*)[self viewWithTag:TABLE_VIEW_ID];
    UIButton* button = (UIButton*)[self viewWithTag:FILTER_BTN_ID];
    
    CGRect bounds = self.bounds;
    textField.frame = bounds;
    tableView.frame = bounds; 
    button.frame = bounds;
    //31是系统text field 默认高度
    textField.height = 31;
    tableView.top += textField.height;
    tableView.height -= textField.height;
    
    button.width = 0;
    button.left += self.width - button.width;
    button.height = textField.height;
    textField.width -= button.width;
}
@end



@implementation WeiboAtController
@synthesize tableView;
@synthesize textField;
@synthesize button;

@synthesize filterString;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        atArraySource = [[NSMutableArray alloc] init];
        atArrayTarget = [[NSMutableArray alloc] init];
        self.filterString = @"";
        textViewTextTipState = NO;
    }
    return self;
}

-(void) dealloc
{
    [atArraySource release];
    [atArrayTarget release];
    [filterString release];
    
    [textField release];
    [tableView release];
    [button release];

    [weibo release];
    [super dealloc];
}

-(void) setWeiboId:(int)weibo_ callback:(id)callback_ sel:(SEL)sel_
{
    callback = callback_;
    sel = sel_;
    
    if (weibo_ == SNS_ID_SINA_WEIBO) {
        [weibo release];
        weibo = [[SinaWeibo alloc ] init ];
    } 
//    else if (weibo_ == SNS_ID_TENC_WEIBO) {
//        [weibo release];
//        weibo = [[TencWeibo alloc  ] init ];
//    } 
    else if (weibo_ == SNS_ID_QQ_SHARE) {
        [weibo release];
        weibo = nil;//[[QQShare alloc ] init];
    } else {
        assert( false);
    }
    error = false;
    hasNext = true;
    pageCurrent = [weibo getFriendsFirstIntvalue];
    reqnum = [weibo getFriendsMaxReqnum];
    [weibo getFriends:self page:(pageCurrent++) reqnum:reqnum];
}

-(void) reflashTargetArray {
    @synchronized(self) {
        [atArrayTarget removeAllObjects];
        for (WeiboUserNode* user in atArraySource) {
            if ((!filterString || filterString.strip.length<=0) || textViewTextTipState ||
                [user.atNameScreen.lower rangeOfString:filterString.lower].location != NSNotFound ||
                [user.atName.lower rangeOfString:filterString.lower].location != NSNotFound) {
                [atArrayTarget addObject:user];
            }
        }
    }
}

-(void) getWeiboFriendsError:(WeiboBase*)weibo
{
    error = true;
}
-(void) getWeiboFriendsCallback:(WeiboBase*)weibo alist:(NSArray*)alist hasNext:(BOOL)hasNext_ nextCursor:(int)cursor_
{    
    [atArraySource addObjectsFromArray:alist];
    [self reflashTargetArray];
    hasNext = hasNext_;
    [self.tableView reloadData];
}

-(void) clearDataList {
    [atArraySource removeAllObjects];
    [atArrayTarget removeAllObjects];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
    DEF_didReceiveMemoryWarning;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    tableView.delegate = self;
    tableView.dataSource = self;

    textField.delegate = self;
    [button addTarget:self action:@selector(filterButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    
    if (textField.text || textField.text.length<=0) {
        textField.text = @"键入关键词检索...";
        self.textField.textColor = [UIColor grayColor];
        textViewTextTipState = YES;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
	return YES;
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return atArrayTarget.count + (hasNext ? 1 : 0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView2 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    }
    
    cell.detailTextLabel.text = nil;
    cell.detailTextLabel.textColor = [UIColor lightGrayColor];
    int row = indexPath.row;
    if (row < atArrayTarget.count) {
        WeiboUserNode* user = [atArrayTarget objectAtIndex:indexPath.row];
        cell.textLabel.text = [NSString stringWithFormat:@"@%@", user.atNameScreen];
        if ([user.atNameScreen compare:user.atName] != 0) {
            cell.detailTextLabel.text = user.atName;
        }
    } else {
        cell.textLabel.text = [NSString stringWithFormat:@"更多..."];
    }
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"Nib name" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    int row = indexPath.row;
    if (row < atArrayTarget.count) {
        WeiboUserNode* user = [atArrayTarget objectAtIndex:indexPath.row];
        [callback performSelector:sel withObject:user];
        //[self dismissModalViewControllerAnimated:true];
        
    } else {
        if (![weibo isinWorking]) {
            [weibo getFriends:self page:(pageCurrent++) reqnum:reqnum];
        }
    }
}



-(void)filterButtonPressed:(id)sender {
    //filterButtonPressed FILTER_BTN_ID
    NSString* text = self.textField.text.strip;
    self.filterString = text;
    [self reflashTargetArray];
    [self.tableView reloadData];
}


#pragma mark - UITextFieldDelegate delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textFieldx {
    if (textViewTextTipState) {
        textViewTextTipState = NO;
        self.textField.text = @"";
        self.textField.textColor = [UIColor blackColor];
    }
    return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textFieldx {
    if (self.textField.text || textField.text.length<=0) {
        textField.text = @"键入关键词检索...";
        self.textField.textColor = [UIColor grayColor];
        textViewTextTipState = YES;
    }
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // return NO to not change text
    NSString* text = self.textField.text;
    NSString* a = [text substringToIndex:range.location];
    NSString* b = [text substringFromIndex:range.location+range.length];
    text = [NSString stringWithFormat:@"%@%@%@", a, string, b];
    self.filterString = text.strip;
    [self reflashTargetArray];
    [self.tableView reloadData];
    return YES;
}
@end

